<template>
  <!-- 订单筛选门店 -->
  <div :class="$style.filtterOrder">
    <FormContainer :column="4">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item prop="officeCode" label="办事处" :span="24/4*2">
          <SearchSelectPicker
            url="/call-center/api/v1/mscInfo/office/ref/page"
            method="get"
            placeholder="请选择办事处"
            lable-name="name"
            value-name="code"
            :value.sync="formData.officeCode"
            multiple
            collapse-tags
            clearable
          ></SearchSelectPicker>
        </el-form-item>
        <el-form-item prop="distributorCode" label="经销商">
          <SearchSelectPicker
            ref="agentSelect"
            url="/call-center/api/v1/mscInfo/dealer/ref/page"
            method="get"
            placeholder="请选择经销商"
            :params="{query:{},type:0}"
            lable-name="name"
            value-name="code"
            custom-name="codeOrName"
            :value.sync="formData.distributorCode"
            :current-id.sync="distributorId"
            clearable
            @selectChange="selectChangeDealerHandle"
          ></SearchSelectPicker>
        </el-form-item>
        <el-form-item prop="storeCode" label="门店">
          <SearchSelectPicker
            ref="agentSelect"
            :disabled="!distributorId"
            :url="'/call-center/api/v1/mscInfo/shop/list/'+distributorId"
            method="get"
            placeholder="请选择门店"
            lable-name="name"
            value-name="code"
            custom-name="codeOrName"
            :must-pid="true"
            :parent-id="distributorId"
            :value.sync="formData.storeCode"
            clearable
          ></SearchSelectPicker>
        </el-form-item>
        <el-form-item prop="createTime" label="送装完成时间">
          <el-date-picker
            v-model="formData.createTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            opt
            :limite="new Date()"
            operator=">"
          />
        </el-form-item>
        <el-form-item prop="orderDate" label="购买时间">
          <el-date-picker
            v-model="formData.orderDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            opt
            :limite="new Date()"
            operator=">"
          />
        </el-form-item>
        <el-form-item prop="orderAmount" label="购买金额">
          <el-input v-model="formData.orderAmount[0]" style="width:46%" number clearable />
          <el-input v-model="formData.orderAmount[1]" style="width:46%" number clearable />
        </el-form-item>
        <!-- 后端接口暂未提供该字段 -->
        <el-form-item prop="orderNum" label="抽取订单量">
          <el-input v-model.trim="formData.orderNum" v-number-input clearable />
        </el-form-item>
        <el-form-item>
          <Button @click="$refs.form.resetFields()">重置</Button>
          <Button type="primary" @click="queryHandle">查询</Button>
        </el-form-item>
      </el-form>
    </FormContainer>
    <div class="button-container" style="padding-top:0">
      <el-form label-width="80px">
        <el-form-item label="回访对象">
          <el-select v-model="addData.visitPeople" placeholder="请选择回访对象" clearable filterable>
            <el-option label="顾客" :value="0" />
            <el-option label="收货人" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <Button type="primary" :loading="loading" @click="confrimAdd">确认新增</Button>
      <!-- <Button type="danger" @click="delet">删除</Button> -->
      <i></i>
      <Button type="primary" @click="next">下一步</Button>
    </div>
    <div class="table-list-box">
      <table-box
        ref="table"
        :class="'checkbox_table'+(paginationHidden?' hidden_page':'') "
        no-request
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :other-raw="otherRaw"
        :selected-arry="selectedAry"
        @data-change="getTableData"
        @selection-change="selectionChange"
      >
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column prop="orderCode" label="订单编号"></el-table-column>
        <el-table-column prop="officeName" label="办事处"></el-table-column>
        <el-table-column prop="distributorName" label="经销商"></el-table-column>
        <el-table-column prop="storeName" label="门店"></el-table-column>
        <el-table-column prop="customerName" label="顾客姓名"></el-table-column>
        <el-table-column prop="contactNumber" label="联系电话"></el-table-column>
        <el-table-column prop="consigneeName" label="收货人"></el-table-column>
        <el-table-column prop="consigneePhone" label="收货人电话"></el-table-column>
        <el-table-column prop="orderAmount" label="购买金额"></el-table-column>
      </table-box>
    </div>
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import { mapState, mapMutations } from 'vuex'
import { filtersRaw, parseTime } from '@/utils'
import { callBackTaskAddBatchObj } from '@/api/callBackTask'
export default {
  name: 'FiltOrdForShop',
  components: {
    FormContainer,
    Button,
    SearchSelectPicker
  },
  data() {
    const validatorOrederNum = (r, v, c) => {
      if (v !== '' && v <= 0) {
        c(new Error('订单抽取量不能小于等于零'))
      } else {
        c()
      }
    }
    return {
      loading: false,
      distributorId: '',
      otherFilters: null,
      formData: {
        officeCode: [],
        distributorCode: '',
        storeCode: '',
        orderDate: [],
        createTime: [],
        orderNum: '',
        orderAmount: []
      },
      paginationHidden: false,
      addSuccess: false,
      formRules: {
        orderNum: [{ validator: validatorOrederNum, trigger: 'change' }]
      },
      selectedAry: [],
      otherRaw: {},
      tableConfig: {
        interfacePath: '/call-center/api/v1/callBackRetailOrder/page',
        pageFlag: true,
        sort: 'orderTime',
        order: 'desc',
        hideFuncBar: true,
        tablePage: [10, 20, 30, 50, 80, 100, 200, 300, 500, 1000, 2000, 3000],
        // 表格字段动态配置
        setting: []
      },
      addData: {
        visitPeople: ''
      }
    }
  },
  computed: {
    ...mapState({
      taskId: function(state) {
        return state.taskForm.form[this.$route.query.id] ? state.taskForm.form[this.$route.query.id].basic.id : ''
      },
      step: function(state) {
        return state.taskForm.form[this.$route.query.id] ? state.taskForm.form[this.$route.query.id].step : 1
      }
    })
  },
  methods: {
    ...mapMutations({
      SET_STEP: 'taskForm/SET_STEP'
    }),
    // 查询
    queryHandle() {
      const list = []

      for (const [key, value] of Object.entries(this.formData)) {
        if (value === '' || value === undefined || value === null || key === 'orderNum') {
          continue
        }
        if (Array.isArray(value)) {
          if (value.length <= 0) {
            continue
          }
          switch (key) {
            case 'orderDate':
              list.push(filtersRaw(key, parseTime(value[0], '{y}-{m}-{d}'), '>='))
              list.push(filtersRaw(key, parseTime(value[1], '{y}-{m}-{d}'), '<='))
              break
            case 'createTime':
              list.push(filtersRaw(key, parseTime(value[0], '{y}-{m}-{d} 00:00:00'), '>='))
              list.push(filtersRaw(key, parseTime(value[1], '{y}-{m}-{d} 23:59:59'), '<='))
              break
            case 'orderAmount':
              if (value[0] !== '') {
                list.push(filtersRaw(key, value[0], '>='))
              }
              if (value[1] !== '') {
                list.push(filtersRaw(key, value[1], '<='))
              }
              break
            default:
              list.push(filtersRaw(key, `[${value.join(',')}]`, 'in'))
              break
          }
        } else {
          list.push(filtersRaw(key, value, '='))
        }
      }
      this.otherFilters = list
      const otherRaw = {}
      if (this.formData.orderNum > 0) {
        otherRaw.orderNum = this.formData.orderNum
      }
      this.otherRaw = otherRaw
      this.refresh()
    },

    // 确认新增
    confrimAdd() {
      if (!this.addData.visitPeople && this.addData.visitPeople !== 0) {
        return this.$message.info('请先选择回访对象')
      }
      if (this.selectedAry.length === 0) {
        return this.$message.info('请至少选择一条数据')
      }
      this.loading = true
      this.selectedAry.forEach(e => {
        e.callBackObject = this.addData.visitPeople
        e.taskId = this.taskId
        e.disCode = e.distributorCode
        e.disName = e.distributorName
        e.shopCode = e.storeCode
        e.shopName = e.storeName
        e.customerPhone = e.contactNumber
        e.receiver = e.consigneeName
        e.receiverPhone = e.consigneePhone
      })
      callBackTaskAddBatchObj({
        objectMethod: 2,
        callBackObjectOfflineDTOList: this.selectedAry
      })
        .then(res => {
          this.loading = false
          if (res.success === 1) {
            this.addSuccess = true
            // this.refresh()
          }
        })
        .catch(er => {
          this.loading = false
        })
    },
    // 删除
    delet() {
      if (this.selectedAry.length === 0) {
        return this.$message.info('请选择要删除的数据')
      }
      var that = this
      this.$msgbox({
        title: '确认删除',
        showCancelButton: true,
        type: 'warning',
        message: '确定删除所选择任务？'
      })
        .then(() => {
          that.refresh('onPage')
        })
        .catch(e => e)
    },
    next() {
      if (!this.addSuccess) {
        return this.$message.info('请先新增任务对象')
      }
      this.SET_STEP({ id: this.$route.query.id, step: this.step + 1 })
    },
    refresh(type) {
      this.$refs.table.$children.forEach(e => {
        if (
          e.$el.className &&
          e.$el.className.indexOf('pagination-container') > -1
        ) {
          if (this.formData.orderNum) {
            e.params.rows = parseInt(this.formData.orderNum)
          } else {
            e.params.rows = e.pageSizes[0]
          }
        }
      })
      this.$nextTick(() => {
        this.$refs.table.initTableData(type)
      })
    },
    selectionChange(val) {
      this.selectedAry = val
    },
    getTableData() {
      this.paginationHidden = !!this.formData.orderNum
    },
    // 经销商变化清空门店数据
    selectChangeDealerHandle() {
      this.$set(this.formData, 'storeCode', '')
    }
  }
}
</script>
<style lang='scss' module>
.filtterOrder{
  & tr{
    background-color: white !important;
  }
}
</style>
